package com.example.lyxxx.music;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;
import java.util.zip.Inflater;

/**
 * 音乐列表的adaper
 */

public class MusicApdater extends RecyclerView.Adapter<MusicApdater.MusicHolder> {
    //监听事件对象的定义
    private OnItemClickListener mOnItemClickListener;
    private Context context;
    private LayoutInflater inflater;
    private List<MusicBean> musicList;

    public MusicApdater(Context context, List<MusicBean> musicList) {
        this.context = context;
        this.musicList = musicList;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public MusicHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = inflater.inflate(R.layout.item, null);
        MusicHolder musicHolder = new MusicHolder(v);
        return musicHolder;
    }

    @Override
    public void onBindViewHolder(final MusicHolder holder, int position) {
        if (musicList.get(position).getSong() != null) {
            //如果歌曲存在歌曲的名字，则获取名字作为歌名，否则用"歌曲名字信息丢失"作为名字
            holder.musicName.setText(musicList.get(position).getSong().toString());
        } else {
            holder.musicName.setText("歌曲名字信息丢失");
        }

        //监听事件-------------对外面暴露一个监听接口，对整个item进行监听
        if (mOnItemClickListener != null) {
            //为ItemView设置监听器
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = holder.getPosition(); // 1
                    mOnItemClickListener.onItemClick(holder.itemView, position); // 2
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return musicList.size();
    }

    public class MusicHolder extends RecyclerView.ViewHolder {
        private TextView musicName;

        public MusicHolder(View itemView) {
            super(itemView);
            musicName = (TextView) itemView.findViewById(R.id.music_item_name);
        }
    }

    //新建监听接口---------------
    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    public void setOnItemClickListener(MusicApdater.OnItemClickListener mOnItemClickListener) {
        this.mOnItemClickListener = mOnItemClickListener;
    }
}
